package com.learn.springboot.config;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.learn.springboot.dao.request.ResponseManage;
import com.learn.springboot.dao.response.ErrorCodeEnum;
import com.learn.springboot.service.utils.JacksonUtil;
import com.learn.springboot.service.utils.TokenUtil;

/**
 * @author suzheng
 * @date 2024-05-16
 **/
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!checkToken(request)) {
            return onAccessDenied(response);
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }



    public boolean checkToken(HttpServletRequest request) {
        String token = request.getHeader(TokenUtil.ADMIN_TOKEN);
        return token != null && TokenUtil.checkToken(token);
    }

    protected boolean onAccessDenied(ServletResponse servletResponse) throws Exception {
        servletResponse.setContentType("application/json;charset=UTF-8");
        servletResponse.setCharacterEncoding("utf-8");
        servletResponse.getWriter().write(JacksonUtil.toJson(ResponseManage.fail(ErrorCodeEnum.SESSION_TIMEOUT)));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
